import { useState } from 'react'
import { MoreOutlined } from '@ant-design/icons'
import { Button, Popover, Space, message, Input, Select } from 'antd'
import { deleteBookApi } from '@/api/books'
import Modal from '@/component/modal/modal'


function More(props: {
  data: DataInterface
  index: number
  cb: (data: DataInterface, status: string, index: number) => void
}) {
  const { data, cb, index } = props

  const [open, setOpen] = useState<boolean>(false)

  const handleOpenChange = (newOpen: boolean) => {
    setOpen(newOpen)
  }

  return (
    <Popover
      content={<PopoverContent books={data} cb={cb} index={index} />}
      trigger="click"
      open={open}
      onOpenChange={handleOpenChange}
    >
      <MoreOutlined onClick={(e) => e.preventDefault()} />
    </Popover>
  )
}

interface DataInterface {
  [key: string]: string
}

function PopoverContent(props: {
  books: DataInterface
  index: number
  cb: (data: DataInterface, status: string, index: number) => void
}) {
  const { books, cb, index } = props

  // 编辑、删除书签
  const handleClick = async (status: string) => {
    if (status === 'edit') {
      showModal()
    } else if (status === 'delete') {
      const { code, msg } = await deleteBookApi({ book_id: books.id })
      if (code !== 200) return message.error(msg)
      message.success('删除成功')
      // 回调操作
      cb(books, 'delete', index)
    }
  }

  const [isModalOpen, setIsModalOpen] = useState(false)

  // 显示弹窗
  const showModal = () => setIsModalOpen(true)

  // 编辑书签回调
  const editCallback = (data: DataInterface) => cb(data, 'edit', index)

  return (
    <>
      <Space.Compact direction="vertical">
        <Button type="primary" block size="small" onClick={() => handleClick('edit')}>
          修改书签
        </Button>
        <Button type="primary" block size="small" danger onClick={() => handleClick('delete')}>
          删除书签
        </Button>
      </Space.Compact>
      <Modal
        isModalOpen={isModalOpen}
        setIsModalOpen={setIsModalOpen}
        books={books}
        cb={editCallback}
      />
    </>
  )
}

export default More
